<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { headersStore } from '@/stores/apiHeader'
import { DEFAULT_ECHARTS_FONTSIZE,DIALOG_ECHARTS_FONTSIZE } from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const language_id = headersStore().language_id
const fontSize = dialogInfo.visible ? DIALOG_ECHARTS_FONTSIZE : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}
const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()

const legendData = []
const series = props.chartData.data?.map((item) => {
  legendData.push(item.name)
  return {
    name: item.name,
    type: 'line',
    data: item.value,
    symbolSize: changePixelSize(7),
    symbol: 'circle',
    tooltip: {
      valueFormatter: function (value) {
        return value + ' %'
      },
    },
  }
})
const xData = ref([])
let option = null
let dataZoom = []
// let series = []
let myChart: echarts.ECharts
const createChart = () => {
  // 判断是否能获取到dom,如果不能直接结束
  const theDom = document.getElementById(props.chartData.name)
  if (!theDom) {
    return ''
  }
  myChart = echarts.init(document.getElementById(props.chartData.name))
  option = {
    tooltip: {
      trigger: 'axis',
      textStyle: {
        //提示框浮层的文本样式。
        color: '#fff', //文字的颜色。
        fontStyle: 'normal', //文字字体的风格。
        fontWeight: 'normal', // 文字字体的粗细 string [ normal  bold bolder lighter]   number
        fontSize: changePixelSize(fontSize),
      },
      position:
        language_id == 'zh-cn'
          ? function (point, params, dom, rect, size) {
              const [pointX, pointY] = point
              const [boxWidth, boxHeight] = size.contentSize
              const x = boxWidth > pointX ? pointX + 10 : pointX - boxWidth - 10
              const y = boxHeight > pointY ? 5 : pointY - boxHeight
              return [x, y]
            }
          : function (pos, params, dom, rect, size) {
              // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
              var obj = { top: 30 }
              obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10
              return obj
            },
      backgroundColor: 'rgba(0,0,0,0.7)',
    },
    legend: {
      data: legendData,
      itemWidth: changePixelSize(20.2),
      itemHeight: changePixelSize(10.5),
      textStyle: {
        fontSize: changePixelSize(fontSize),
        lineHeight: changePixelSize(15),
        color: '#fff',
      },
      type: 'scroll',
      pageIconColor: '#00f9f5',
      pageIconSize: changePixelSize(fontSize),
    },
    grid: {
      left: '5%',
      right: '10%',
      bottom: '12%',
      top: '20%',
      containLabel: true,
    },

    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.chartData?.xAxis?.data,
      axisTick: {
        show: false, // 关闭刻度线
      },
      axisLine: {
        show: false, // 关闭轴线
      },
      axisLabel: {
        color: '#fff', // 设置 X 轴标签字体颜色
        interval: 0, // 强制显示所有标签
        fontSize: changePixelSize(fontSize),
        margin: changePixelSize(fontSize), // 调整标签与轴线的距离
        formatter:dialogInfoVisible==false? function (str: any) {
          // 中文算2,英文算1,数到maxLength截取,然后打...
          let count = 0
          let result = ''

          for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i)
            count += /[\u4E00-\u9FA5]/g.test(char) ? 2 : 1

            if (count > 8) {
              result += '...'
              break
            }

            result += char
          }
          return result
        }:function (str: any) {
          // 中文算2,英文算1,数到maxLength截取,然后打...
          let count = 0
          let result = ''

          for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i)
            count += /[\u4E00-\u9FA5]/g.test(char) ? 1 : 1

            if (count > 8) {
              result += '...'
              break
            }

            result += char
          }
          return result
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: changePixelSize(fontSize),
        formatter: function (params) {
          return params.toFixed(2) + '%'
        },
        color: '#fff',
      },
      splitLine: {
        lineStyle: {
          color: '#123545', // 分割线颜色为灰色
        },
      },
    },
    color: [
      '#CC5F30',
      '#00A0E9',
      '#1E49AD',
      '#E6AF08',
      '#87FBF4',
      '#1E49AD',
      '#6054FF',
    ],
    dataZoom: [
      {
        type: 'inside',
        show: false,
        xAxisIndex: [0],
        zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
        moveOnMouseWheel: true, // 开启鼠标滚轮窗口平移
        moveOnMouseMove: true, // 开启鼠标移动窗口平移
        start: 0,
        end:
          props.chartData.xAxis.data.length > 3
            ? ~~((4 / props.chartData.xAxis.data.length) * 100)
            : 100,

        showDataShadow: false,

        textStyle: {
          color: '#ccd7d7',
        },
      },
    ],
    series: series,
  }

  // 绘制图表
  myChart.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    createChart()
  })
})

// 销毁前释放内存
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})

watch(
  () => props.chartData,
  () => {
    nextTick(() => {
      createChart()
    })
  },
  { deep: true }
)
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>

<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: 260px;
  .chart {
    width: 100%;
    height: 100%;
  }
}
.dialog-box {
  height: calc(
    500px - 45px
  );
}
</style>
